package com.haotunet.app.goldtreasure.activity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.db.DBOpenHelper;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.UserInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.Config;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.utils.Utils;
import com.haotunet.app.goldtreasure.views.TitleView;
import com.umeng.message.UmengRegistrar;

import java.util.Timer;
import java.util.TimerTask;

import cn.tongdun.android.shell.FMAgent;

public class FindPwdActivity extends BaseActivity implements OnClickListener {
    private TitleView mTitleView;
    private Button btnNext;
    private EditText etPhone, etVericode;
    private TextView txtDesCription;
    private TextView mFetchBtn;
    private ImageView ivDeletePhone;
    private ActionUtil actionUtil;
    private int curTime;
    private Timer timer;
    private final int FORGET_PASSWORD = 1;
    private int type;
    private String wechatCode;
    private ShareStore mStore;
    private Handler doActionHandler = new Handler() {

        @SuppressWarnings("deprecation")
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    if (curTime == 0) {
                        timer.cancel();
                        mFetchBtn.setText("重新获取");
                        mFetchBtn.setTextColor(FindPwdActivity.this.getResources().getColor(R.color.title_bg));
                        mFetchBtn.setEnabled(true);
                    } else {
                        mFetchBtn.setText(curTime + "s" + getString(R.string.repeat_after_sixty_seconds));
                        mFetchBtn.setTextColor(FindPwdActivity.this.getResources().getColor(R.color.title_bg));
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_findpwd);
        mStore = new ShareStore(this);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        String describtion = intent.getStringExtra("describtion");
        String btnText = intent.getStringExtra("btnText");
        wechatCode = intent.getStringExtra("wechatCode");
        type = intent.getIntExtra("type", 0);
        actionUtil = new ActionUtil(FindPwdActivity.this);
        mTitleView = (TitleView) findViewById(R.id.title_view);
        mTitleView.getTitletextView().setVisibility(View.VISIBLE);
        mTitleView.getTitletextView().setText(getString(R.string.check_phonenum));
        mTitleView.getBackView().setVisibility(View.VISIBLE);
        mTitleView.getBackView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        txtDesCription = (TextView) findViewById(R.id.txt_description);
        txtDesCription.setText(describtion);
        btnNext = (Button) findViewById(R.id.btn_next);
        btnNext.setText(btnText);
        etPhone = (EditText) findViewById(R.id.et_phoneNum);
        etVericode = (EditText) findViewById(R.id.et_vericode);
        mFetchBtn = (TextView) findViewById(R.id.btn_get_vericode);
        ivDeletePhone = (ImageView) findViewById(R.id.findpwd_iv_delete_phone);
        btnNext.setOnClickListener(this);
        mFetchBtn.setOnClickListener(this);
        ivDeletePhone.setOnClickListener(this);
        initEditext();
    }

    private void initEditext() {
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    ivDeletePhone.setVisibility(View.VISIBLE);
                } else {
                    ivDeletePhone.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.findpwd_iv_delete_phone:
                etPhone.setText("");
                break;
            case R.id.btn_get_vericode:
                String phone = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    UIHelper.showToast(FindPwdActivity.this, getString(R.string.please_enter_phone_number));
                    return;
                }
                if (!Utils.isCellularPhoneNumber(phone)) {
                    UIHelper.showToast(FindPwdActivity.this, getString(R.string.wrong_phone_number));
                    return;
                }
                if (type == FORGET_PASSWORD) {
                    getSmsVF(phone);
                } else {
                    getWeChatVeriCode(phone);
                }

                break;
            case R.id.btn_next:
                phone = etPhone.getText().toString().trim();
                String vericode = etVericode.getText().toString().trim();
                if (!Utils.isVeriCode(vericode) || TextUtils.isEmpty(vericode)) {
                    UIHelper.showToast(FindPwdActivity.this, getString(R.string.vericode_format));
                    return;
                }
                if (type == FORGET_PASSWORD) {
                    checkCode(phone, vericode);
                } else {
                    weChatLogin(phone, vericode);
                }
                break;

            default:
                break;
        }
    }

    private void weChatLogin(final String phone, String vericode) {
        String device_token = UmengRegistrar.getRegistrationId(FindPwdActivity.this);
        String imei = Config.getImei(FindPwdActivity.this);
        String blackBox = FMAgent.onEvent(this);
        String channelId = Config.getStringMetaData(FindPwdActivity.this, "UMENG_CHANNEL");
        actionUtil.wechatLogin(wechatCode, phone, device_token, imei, vericode, blackBox, channelId);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {
            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                UserInfo info = (UserInfo) model;
                if (info == null) {
                    UIHelper.showToast(FindPwdActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (info.getErrorMsg() != null) {
                    UIHelper.showToast(FindPwdActivity.this, info.getErrorMsg());
                } else {
                    if ("true".equals(info.getStatus())) {
                        storeUserInfo(info);
                        skipToMain();
                        FindPwdActivity.this.finish();
                    } else {
                        ActivityUtils.gotoWechatRegister(FindPwdActivity.this, phone, wechatCode);
                    }
                }
            }
        });

    }

    private void skipToMain() {
        Intent intent = new Intent();
        intent.setClass(FindPwdActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("type", "wechatLogin");
        startActivity(intent);
    }

    private void storeUserInfo(UserInfo info) {
        mStore.putBoolean(Strs.IS_LOGIN, true);
        mStore.putInt(Strs.IS_HAD_TRADING_PWD, info.getIsHadTradingPassword());
        mStore.putInt(Strs.IS_HAD_BANK_CARD, info.getIsHadBankCard());
        mStore.commit();
        DBOpenHelper helper = new DBOpenHelper(FindPwdActivity.this);
        SQLiteDatabase db = helper.getReadableDatabase();
        String mobile = info.getUserName();
        String sql = "select * from HJB_USER where mobile = " + "'" + mobile + "'";
        Cursor rawQuery = db.rawQuery(sql, null);
        if (rawQuery.getCount() != 0) {
            helper.updateUser(mobile, "0", info);
        } else {
            helper.insertUser("0", info);
        }
    }

    private void getWeChatVeriCode(String phone) {
        String blackBox = FMAgent.onEvent(FindPwdActivity.this);
        String imei = Config.getImei(FindPwdActivity.this);
        actionUtil.getWeChatCode(phone, blackBox, imei);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                if (model == null) {
                    UIHelper.showToast(FindPwdActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    UIHelper.showToast(FindPwdActivity.this, model.getErrorMsg());
                } else {
                    UIHelper.showToast(FindPwdActivity.this, getString(R.string.vericode_send_success));
                    setTimerTask();
                    mFetchBtn.setEnabled(false);
                }
            }
        });
    }

    private void checkCode(final String phone, final String vericode) {
        actionUtil.checkVeriCode(phone, vericode);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                if (model == null) {
                    UIHelper.showToast(FindPwdActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    UIHelper.showToast(FindPwdActivity.this, model.getErrorMsg());
                } else {
                    Intent intent = new Intent(FindPwdActivity.this, ResetPwdActivity.class);
                    intent.putExtra("phone", phone);
                    intent.putExtra("code", vericode);
                    intent.putExtra("type", 1);
                    startActivityForResult(intent, 1);
                    overridePendingTransition(R.anim.anim_push_in, R.anim.anim_push_in);
                }
            }
        });
    }

    private void getSmsVF(String phone) {
        String blackBox = FMAgent.onEvent(FindPwdActivity.this);
        String imei = Config.getImei(FindPwdActivity.this);
        actionUtil.getFindPwdCode(phone, blackBox, imei, 1);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                if (model == null) {
                    UIHelper.showToast(FindPwdActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    UIHelper.showToast(FindPwdActivity.this, model.getErrorMsg());
                } else {
                    UIHelper.showToast(FindPwdActivity.this, getString(R.string.vericode_send_success));
                    setTimerTask();
                    mFetchBtn.setEnabled(false);
                }
            }
        });
    }

    private void setTimerTask() {
        curTime = 60;
        timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {

                Message msg = new Message();
                msg.what = 1;
                doActionHandler.sendMessage(msg);
                curTime--;
            }
        }, 0, 1000);
    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        super.onActivityResult(arg0, arg1, arg2);
        if (arg0 == 1 && arg1 == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }
}
